import { HttpException, Injectable } from '@nestjs/common';
import { CreateCollectDto } from './dto/create-collect.dto';
import { PrismaService } from 'src/prisma/prisma.service';

@Injectable()
export class CollectService {
  constructor(private readonly prismaService: PrismaService) {}
  async create(createCollectDto: CreateCollectDto, userId: number) {
    try {
      const res = await this.prismaService.collectMessageHistory.findFirst({
        where: {
          messageId: +createCollectDto.messageId,
        },
      });
      console.log(res);
      if (res) return '已收藏过了';

      await this.prismaService.collectMessageHistory.create({
        data: {
          userId: +userId,
          messageId: +createCollectDto.messageId,
          type: +createCollectDto.type,
        },
      });

      return '收藏成功';
    } catch (error) {
      throw new HttpException(error, 500);
    }
  }

  findAll(userId: number) {
    return this.prismaService.collectMessageHistory.findMany({
      where: {
        userId,
      },
      include: {
        message: {
          select: {
            content: true,
          },
        },
      },
    });
  }

  findOne(id: number) {
    return this.prismaService.collectMessageHistory.findFirst({
      where: {
        id,
      },
      include: {
        message: {
          select: {
            content: true,
          },
        },
      },
    });
  }

  async remove(id: number) {
    try {
      await this.prismaService.collectMessageHistory.delete({
        where: {
          id,
        },
      });

      return '删除成功';
    } catch (error) {
      throw new HttpException(error, 500);
    }
  }
}
